// store/modules/orders.js
export default {
    namespaced: true,
    state: () => ({
        processing: [],        // 进行中的订单
        pendingPayment: [],    // 待付款订单
        toReview: [],          // 待评价订单
        toView: []             // 待使用订单
    }),
    mutations: {
        SET_ORDERS(state, { status, orders }) {
            state[status] = orders;
        },
        ADD_PENDING_ORDER(state, order) {
            state.toView.unshift(order);
        },
        UPDATE_ORDER_STATUS(state, { orderId, newStatus }) {
            Object.keys(state).forEach(statusKey => {
                const idx = state[statusKey].findIndex(o => o.orderId === orderId);
                if (idx > -1) {
                    state[statusKey][idx].status = newStatus;
                }
            });
        },
        CLEAR_ALL_ORDERS(state) {
            Object.keys(state).forEach(key => {
                state[key] = [];
            });
        }
    },
    actions: {
        loadCurrentOrders({ commit }) {
            const ordersList = uni.getStorageSync('ordersList') || [];

            commit('SET_ORDERS', { status: 'processing', orders: ordersList.filter(o => o.status === 'processing') });
            commit('SET_ORDERS', { status: 'pendingPayment', orders: ordersList.filter(o => o.status === 'pendingPayment') });
            commit('SET_ORDERS', { status: 'toReview', orders: ordersList.filter(o => o.status === 'toReview') });
            commit('SET_ORDERS', { status: 'toView', orders: ordersList.filter(o => o.status === 'pendingUse') });
        },
        addNewPendingOrder({ commit }, order) {
            commit('ADD_PENDING_ORDER', order);
            uni.setStorageSync('ordersList', [...uni.getStorageSync('ordersList') || [], order]);
        },
        clearAllOrders({ commit }) {
            commit('CLEAR_ALL_ORDERS');
            uni.setStorageSync('ordersList', []);
        }
    },
    getters: {
        formattedOrders: (state) => {
            const now = Date.now();
            return state.toView.map(order => {
                const scheduledStartTime = order.scheduledStartTime;
                const tenMinutesLater = scheduledStartTime + 10 * 60 * 1000;
                return {
                    ...order,
                    isTimedOut: now >= tenMinutesLater
                };
            });
        }
    }
};
